package com.study.shirojwtredis.shiro.realm;

import com.study.shirojwtredis.domain.Account;
import com.study.shirojwtredis.shiro.provider.AccountProvider;
import com.study.shirojwtredis.shiro.token.PasswordToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/*********************************************************
 * @Author ONE_LLX
 * @Description //TODO 
 * @Date 18:13 2019/11/16
 * @Class PasswordRealm
 * @Version v1.0
 *********************************************************/
public class PasswordRealm extends AuthorizingRealm {


    @Autowired
    @Qualifier("accountProvider")
    private AccountProvider accountProvider;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("身份验证");
        PasswordToken upToken = null;
        //向下转型
        if (token instanceof PasswordToken) {
            upToken = (PasswordToken) token;
        } else {
            return null;
        }
        /*******************************
         * 登录业务逻辑操作 比如去数据库查
         * 这里简单处理
         *******************************/
        Account account = accountProvider.loadAccount(upToken.getAppId());
        String passwd= new Md5Hash(String.valueOf(upToken.getPassword()), account.getSalt(), 10).toString();
        upToken.setPassword(passwd);
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(account.getAccount(),
                account.getPassd(), this.getName());
        return authenticationInfo;
    }

    @Override
    public Class<?> getAuthenticationTokenClass() {
        return PasswordRealm.class;
    }
}
